package com.gz.mylife.app;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.adapter.AssortThirdLevelAdapter;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zl.smartmall.library.IGZAddress;
import com.zl.smartmall.library.ISmartMall;
import com.zl.smartmall.library.listener.GetAssortFirstlevelListener;
import com.zl.smartmall.library.po.AssortFirstLevelInfo;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

public class FragmentAssortment extends BaseActivity implements OnClickListener,OnItemClickListener{
	private static final String REFRESH_TIME = "fragmentassortmen_refresh_time";
	
	private ListView mListView;
	private MyAdapter mAdapter;
	private List<AssortFirstLevelInfo> indexs;
	private List<AssortFirstLevelInfo> secondIndexs;
	private LayoutInflater mInflater;
	private int mCurrentPostion;
	private MyHandler mHandler;
	private GridView mLvSecondLevel;
	private RelativeLayout mHeaderView;
	private ImageView mIvAdPic;
	
	private AssortThirdLevelAdapter mSecondAdapter;

	private DisplayImageOptions mAdOptions;
	private int intpicHight;
	private getAssortListener listener;
	private LinearLayout layout_search;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_assortment);
		setActionbarTitle("商品分类", false);
		listener = new getAssortListener(this);
		ISmartMall.getInstance().getAssortFirstList(IGZAddress.getInstance().getCurrentCommunityID(), listener);
		mInflater = LayoutInflater.from(FragmentAssortment.this);
		mHandler = new MyHandler(this);
		
		indexs = new ArrayList<AssortFirstLevelInfo>();
		secondIndexs = new ArrayList<AssortFirstLevelInfo>();
		mAdOptions = createOptions();
		
		initView();
		WindowManager wm = (WindowManager) FragmentAssortment.this.getSystemService(Context.WINDOW_SERVICE);
		int windowWidth = wm.getDefaultDisplay().getWidth();
		intpicHight = (windowWidth - dip2px(FragmentAssortment.this, 106))/3;
	}
	
	public static int dip2px(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	private DisplayImageOptions createOptions() {
		// TODO Auto-generated method stub
		return new DisplayImageOptions.Builder()
			.showImageForEmptyUri(R.drawable.drawable_recent_white)
			.showImageOnFail(R.drawable.drawable_recent_white)
			.showImageOnLoading(R.drawable.drawable_recent_white)
			.cacheInMemory(true)
			.cacheOnDisk(true)
			.build();
	}

	private void initView() {
		mListView = (ListView) findViewById(R.id.listview);
		mAdapter = new MyAdapter();
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(this);
		mLvSecondLevel = (GridView)findViewById(R.id.gridview);

		mHeaderView = (RelativeLayout) LayoutInflater.from(FragmentAssortment.this).inflate(R.layout.assort_list_header, null);
		mIvAdPic = (ImageView) mHeaderView.findViewById(R.id.iv_ad_pic);
		mIvAdPic.setOnClickListener(this);
		RelativeLayout.LayoutParams params = (LayoutParams) mIvAdPic.getLayoutParams();
		params.height = intpicHight;
		//mLvSecondLevel.addHeaderView(mHeaderView);
		
		layout_search = (LinearLayout)findViewById(R.id.layout_search);
		layout_search.setOnClickListener(this);
		mSecondAdapter = new AssortThirdLevelAdapter(FragmentAssortment.this, secondIndexs);
		mLvSecondLevel.setAdapter(mSecondAdapter);
		mSecondAdapter.notifyDataSetChanged();
		//mSecondAdapter.setListener(this);
		//点击某个类型的商品
		mLvSecondLevel.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(FragmentAssortment.this,AssortmentProductsActivity.class);
				intent.putExtra("brandId", secondIndexs.get(position).getId());
				intent.putExtra("typename", secondIndexs.get(position).getName());
				startActivity(intent);
			}
		});
	}

	private void changePager() {
		if(TextUtils.isEmpty(indexs.get(mCurrentPostion).getPic())){
			mIvAdPic.setVisibility(View.GONE);
		}else{
			mIvAdPic.setVisibility(View.VISIBLE);
			ImageLoader.getInstance().displayImage(indexs.get(mCurrentPostion).getPic(), mIvAdPic, mAdOptions);
		}
		mAdapter.setCurrent(mCurrentPostion);
		mAdapter.notifyDataSetChanged();
		secondIndexs.clear();
		if(indexs.size()>0){
			secondIndexs.addAll(indexs.get(mCurrentPostion).getSecondLists());
		}
		mSecondAdapter.notifyDataSetChanged();
//		mLvSecondLevel.setSelection(0);
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rl_assort_search:
		case R.id.iv_voice_search:
			break;
		case R.id.iv_ad_pic:
			break;
		case R.id.layout_search:
			Intent intentSearch = new Intent(FragmentAssortment.this, ShoppingSearchActivity.class);
			startActivity(intentSearch);
			break;
		default:
			break;
		}
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mHandler.release();
	}
	
	private class MyAdapter extends BaseAdapter{
		private int mCurrentPostion;
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return indexs.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return indexs.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if(convertView == null){
				convertView = mInflater.inflate(R.layout.assortfirstindex_item, null);
				holder = new ViewHolder();
				holder.title = (TextView) convertView.findViewById(R.id.tv_title);
				holder.top = (RelativeLayout) convertView.findViewById(R.id.rl_top);
				holder.selectLine = convertView.findViewById(R.id.select_line);
				holder.selectLine2 = convertView.findViewById(R.id.line3);
				convertView.setTag(holder);
			}else{
				holder = (ViewHolder) convertView.getTag();
			}
			holder.title.setText(indexs.get(position).getName());
			if(position == mCurrentPostion){
				holder.top.setBackgroundResource(R.color.white);
				holder.title.setTextColor(getResources().getColor(R.color.red));
				holder.selectLine.setVisibility(View.VISIBLE);
				holder.selectLine2.setVisibility(View.GONE);
			}else{
				holder.top.setBackgroundResource(R.color.RGB_F2F2F2);
				holder.title.setTextColor(getResources().getColor(R.color.black));
				holder.selectLine.setVisibility(View.GONE);
				holder.selectLine2.setVisibility(View.VISIBLE);
			}
			return convertView;
		}
		
		public void setCurrent(int postion){
			mCurrentPostion = postion;
		}
		
		public class ViewHolder{
			public TextView title;
			public RelativeLayout top;
			public View selectLine;
			public View selectLine2;
		}
		
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		if(position<0){
			return;
		}
		mCurrentPostion = position;
//		mAdapter.setCurrent(mCurrentPostion);
//		mAdapter.notifyDataSetChanged();
		changePager();
//		mHandler.postDelayed(slipping, 100);
		
	}
	
	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		mHandler.removeCallbacks(slipping);
	}
	
	private Runnable slipping = new Runnable() {
		
		@Override
		public void run() {
			int start = mListView.getFirstVisiblePosition();
			if(start < mCurrentPostion){
				mListView.setSelection(start+1);
				mHandler.postDelayed(slipping, 0);
				if(indexs.size() == mListView.getLastVisiblePosition()+1){
					mHandler.removeCallbacks(slipping);
				}
			}else{
				mHandler.removeCallbacks(slipping);
			}
		}
	};
	
	private static class MyHandler extends Handler{
		private FragmentAssortment mOuter;
		
		public MyHandler(FragmentAssortment outer){
			this.mOuter = outer;
		}
		
		public void release(){
			new WeakReference<FragmentAssortment>(mOuter);
		}
		
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 2:
				/*String assortJson = (String) msg.obj;
				try {
					mOuter.indexs.addAll(AssortFirstLevelInfo.parse(new JSONObject(assortJson).getJSONObject("result").getJSONArray("columdetail")));
					mOuter.changePager();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;*/
			case 1:
				List<AssortFirstLevelInfo> infos = (List<AssortFirstLevelInfo>) msg.obj;
				if(infos.size()>0){
					mOuter.indexs.addAll(infos);
					mOuter.changePager();
				}else{
//					mOuter.loadDataFromAssert();
//					mOuter.loadDataFromServer();
				}
				
				break;

			default:
				break;
			}
		}
	}

	private static class getAssortListener extends GetAssortFirstlevelListener {
		private FragmentAssortment mOuter;

		public getAssortListener(FragmentAssortment outer) {
			this.mOuter = outer;
		}

		public void release() {
			new WeakReference<FragmentAssortment>(mOuter);
		}

		@Override
		public void onResponseSuccess(List<AssortFirstLevelInfo> infos) {
			// TODO Auto-generated method stub
			if(mOuter == null){
				return;
			}
			
			mOuter.indexs.addAll(infos);
			mOuter.secondIndexs.addAll(mOuter.indexs.get(0).getSecondLists());
			mOuter.mAdapter.notifyDataSetChanged();
			mOuter.mSecondAdapter.notifyDataSetChanged();
		}

		@Override
		public void onNoMoreData() {
			// TODO Auto-generated method stub
			if(mOuter == null){
				return;
			}
		}

		@Override
		public void onNoNetWork() {
			// TODO Auto-generated method stub
			if(mOuter == null){
				return;
			}
			Toast.makeText(mOuter.getApplicationContext(), Define.MSG_NO_NETWORK, Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onResponseFailed() {
			// TODO Auto-generated method stub
			if(mOuter == null){
				return;
			}
		}
		
	}
	
	
}
